package com.starryx.sim.mvc.lifecycle;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Component
@Order(1)
public class LifecycleManager implements ApplicationRunner {

	private static final Logger log = LogManager.getLogger(LifecycleManager.class);

	@Autowired
	private List<Lifecycle> lifecycles;

	private List<LifecycleWrapper> lifecycleWrappers = new ArrayList<>();

	@Override
	public void run(ApplicationArguments args) throws Exception {
		for (Lifecycle lifecycle : lifecycles) {
			Priority priority = lifecycle.getClass().getAnnotation(Priority.class);
			if (priority == null)
				throw new RuntimeException("模块缺失优先级注解");
			LifecycleWrapper lifecycleWrapper = new LifecycleWrapper(lifecycle, priority.value());
			lifecycleWrappers.add(lifecycleWrapper);
		}
		Collections.sort(lifecycleWrappers);
		for (LifecycleWrapper lifecycleWrapper : lifecycleWrappers) {
			try {

				lifecycleWrapper.getLifecycle().init();
				log.info("模块 {} 的 init 方法执行完毕", lifecycleWrapper.getLifecycle().getClass().getSimpleName());
			} catch (Throwable throwable) {
				throwable.printStackTrace();
			}
		}
	}

	@PreDestroy
	private void shutdown() {
		for (int i = this.lifecycleWrappers.size() - 1; i >= 0; i--) {
			try {
				lifecycleWrappers.get(i).getLifecycle().destroy();
				log.info("模块 {} 的 destroy 方法执行完毕", lifecycleWrappers.get(i).getLifecycle().getClass().getSimpleName());
			} catch (Throwable throwable) {
				throwable.printStackTrace();
			}
		}
	}
}
